package com.zw.yzk.kabu.presenter;

import android.support.v7.app.AppCompatActivity;

import com.zw.yzk.kabu.R;
import com.zw.yzk.kabu.base.BaseSubscriber;
import com.zw.yzk.kabu.data.exception.CustomException;
import com.zw.yzk.kabu.data.network.entity.CheckQrEntity;
import com.zw.yzk.kabu.data.network.task.CheckQrTask;
import com.zw.yzk.kabu.domain.repository.UseCase;
import com.zw.yzk.kabu.management.LoadingDialogManager;
import com.zw.yzk.kabu.mapper.CheckQrCodeMapper;
import com.zw.yzk.kabu.view.view.CheckQrCodeView;

import javax.inject.Inject;
import javax.inject.Named;

/**
 * Created by zhanwei on 2017/3/15.
 */

public class ScanQrCodePresenter implements Presenter {

    private UseCase checkQrCode;
    private AppCompatActivity activity;
    private CheckQrCodeView checkQrCodeView;
    private CheckQrCodeMapper mapper;

    @Inject
    public ScanQrCodePresenter(@Named("checkQrCodeUseCase") UseCase checkQrCode,
                               CheckQrCodeMapper mapper,
                               AppCompatActivity activity) {
        this.checkQrCode = checkQrCode;
        this.activity = activity;
        this.mapper = mapper;
    }

    public void setVeiw(CheckQrCodeView checkQrCodeView) {
        this.checkQrCodeView = checkQrCodeView;
    }

    public void checkQrCode(String serialNumber, String checkCode) {
        checkQrCode.execute(new CheckQrCodeSubscriber(activity), new CheckQrTask(serialNumber, checkCode));
    }

    @Override
    public void resume() {

    }

    @Override
    public void pause() {

    }

    @Override
    public void destroy() {

    }

    private class CheckQrCodeSubscriber extends BaseSubscriber<CheckQrEntity> {

        public CheckQrCodeSubscriber(AppCompatActivity appCompatActivity) {
            super(appCompatActivity);
        }

        @Override
        public void onNext(CheckQrEntity entity) {
            super.onNext(entity);
            checkQrCodeView.checkSuccess(mapper.transfer(entity));
        }

        @Override
        public void onError(Throwable e) {
            super.onError(e);
            if (e instanceof CustomException) {
                checkQrCodeView.checkFailed(((CustomException) e).getErrMsg());
            } else {
                checkQrCodeView.checkFailed(activity.getResources().getString(R.string.invalid_ticket));
            }

        }

        @Override
        public void onCompleted() {
            super.onCompleted();
            LoadingDialogManager.getInstance().dismissLoadingDialog();
        }

        @Override
        public String addErrorMessage() {
            return activity.getResources().getString(R.string.check_qr_code_failed);
        }
    }
}
